﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using MVVMFramework.ViewModel;

namespace MVVMFramework.WPFDemo
{
    class ShellVM : BrowseEntitiesViewModel<User, Role>
    {
        protected override string GetTitle()
        {
            return "MVVM Framewowrk -Demo Application. Users";
        }

        protected override IEnumerable<User> LoadEntities()
        {
            return AppModel.Instance.GetUsers();
        }

        protected override bool CompareEntities(User obj1, User obj2)
        {
            return obj1.UserID == obj2.UserID;
        }

        protected override bool RunRequest(User entity, Requests request, out User result)
        {
            if (request == Requests.Insert)
                entity = new User();

            UserVM vm = new UserVM(entity, request);
            UserView view = new UserView(vm);
            if (view.ShowDialog() == true)
            {
                result = entity;
                return true;
            }

            result = null;
            return false;
        }

        protected override bool DeleteEntity(User entity)
        {
            if (MessageBox.Show(string.Format("Would you like to delete user \"{0}\"?", entity.UserName),
                "Comfirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                return false;

            return AppModel.Instance.DeleteUser(entity.UserID);
        }

        protected override bool HandleDeleteException(Exception ex)
        {
            MessageBox.Show(GetExceptionMessage(ex, false), "Unable to delete user", MessageBoxButton.OK, MessageBoxImage.Error);
            return true;
        }

        protected override bool HandleRunRequestException(Requests request, User entity, Exception ex)
        {
            if (request == Requests.Change)
                MessageBox.Show(GetExceptionMessage(ex, false), "Unable to change user", MessageBoxButton.OK, MessageBoxImage.Error);
            else if (request == Requests.Insert)
                MessageBox.Show(GetExceptionMessage(ex, false), "Unable to insert user", MessageBoxButton.OK, MessageBoxImage.Error);
            else if (request == Requests.Select)
                MessageBox.Show(GetExceptionMessage(ex, false), "Unable to select user", MessageBoxButton.OK, MessageBoxImage.Error);
            else
                MessageBox.Show(GetExceptionMessage(ex, false), "Error", MessageBoxButton.OK, MessageBoxImage.Error);

            return true;
        }

        protected override IEnumerable<Role> LoadDependentEntities(User basicEntity)
        {
            return AppModel.Instance.GetRoles(basicEntity.UserID);
        }

        protected override bool CompareEntities(Role obj1, Role obj2)
        {
            return obj1.RoleID == obj2.RoleID;
        }
    }
}
